import {Component} from '@angular/core';
import {HttpCustomConfig} from "../../service/base/base.http.service";
import {OrderHttpService} from "../../service/http/order.http.service";
import * as dayjs from "dayjs";


@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.less']
})
export class OrderComponent {

  dates: any[] = [];
  dataList: any[] = [];
  pageIndex: number = 1;
  pageSize: number = 50;
  pageTotal: number = 0;
  checkedAmount: number = 0;
  checkUserBackAmount: number = 0;
  orderNo: string = '';
  mobile: string = '';
  userId: string = '';
  setOfCheckedId = new Set<number>();
  checked = false;
  indeterminate = false;
  settleStatus: string[] = [];
  settleStatusList = [
    {value: '', label: '全部状态'},
    {value: 'not_ready', label: '待审核'},
    {value: 'pass', label: '审核通过'},
    {value: 'reject', label: '审核不通过'},
    {value: 'ready', label: '待提现'},
    {value: 'done', label: '已提现'}];
  cpsTo: string[] = [];
  cpsToList = [
    {value: 'zmrs', label: '中免日上'},
    {value: 'jd', label: '京东'},
    {value: 'wfj', label: '王府井'},
    {value: 'gdf', label: 'GDF会员购'},
    {value: 'offlineSunrise', label: '线下日上'},
    {value: 'multiArray', label: '美妆指南针'},
    {value: 'hm', label: 'cdf中免海南'},
    {value: 'cdf', label: 'cdf会员购'},
    {value: 'tb', label: '淘宝客'},
    {value: 'hlms', label: '海旅免税'}];
  orderStatus: string[] = [];
  orderStatusList = [
    {value: [], label: '不限'},
    {value: ['00', 'untreated', 'pre_effective', 'SENT','12'], label: '待生效'},
    {value: ['01', 'effective', 'SUCCESS','14','3'], label: '已生效'},
    {value: ['60', 'expired', 'pre_expired', 'CANCEL','13'], label: '已失效'}];

  constructor(private orderHttpService: OrderHttpService) {
  }

  defaultHttpConfig: HttpCustomConfig = {showLoading: false}
  exportHttpConfig: HttpCustomConfig = {showLoading: false}

  ngOnInit() {
    this.dates = [dayjs().startOf('date').toDate(), dayjs().endOf('date').toDate()];
    this.queryData();
  }

  queryDataInit(): void {
    this.pageIndex = 1;
    this.queryData();
  }

  queryData(): void {
    const startTime = dayjs(this.dates[0]).format('YYYY-MM-DD HH:mm:ss');
    const endTime = dayjs(this.dates[1]).format('YYYY-MM-DD HH:mm:ss');
    this.orderHttpService.queryCpsOrder({
      startTime: startTime,
      endTime: endTime,
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      orderNo: this.orderNo,
      mobile: this.mobile,
      userId: this.userId,
      cpsToList: this.cpsTo,
      orderStatusList: this.orderStatus,
      settleStatusList: this.settleStatus
    }, this.defaultHttpConfig).subscribe((res) => {
      this.dataList = res.data.dataList
      this.pageTotal = res.data.total;
    })
  }

  settle(settleStatus: string): void {

    const ids = [];

    for (let i = 0; i < this.dataList.length; i++) {
      const item = this.dataList[i];
      if (!this.setOfCheckedId.has(item.cpsOrderId)) {
        continue;
      }

      ids.push(item.cpsOrderId);
    }

    //更新订单结算状态
    this.orderHttpService.updateCpsOrder({
      cpsOrderIds: ids,
      settleStatus: settleStatus
    }, this.defaultHttpConfig).subscribe((res) => {
      this.queryDataInit();
      this.onAllChecked(false);
    })

  }

  settleDone(): void {

    const ids = [];

    for (let i = 0; i < this.dataList.length; i++) {
      const item = this.dataList[i];
      if (!this.setOfCheckedId.has(item.cpsOrderId)) {
        continue;
      }

      ids.push(item.cpsOrderId);
    }

    //更新订单结算状态
    this.orderHttpService.settleCpsOrder({
      cpsOrderIds: ids
    }, this.defaultHttpConfig).subscribe((res) => {
      this.queryDataInit();
      this.onAllChecked(false);
    })

  }

  save(data: any): void {
    this.orderHttpService.updateCpsOrder({
      cpsOrderId: data.cpsOrderId,
      userCashBack: data.userCashBack,
      userRebate: data.userRebate
    }, this.defaultHttpConfig).subscribe((res) => {
      this.queryDataInit();
    })
  }

  onAllChecked(value: boolean): void {
    this.dataList.forEach(item => this.updateCheckedSet(item.cpsOrderId, value));
    this.refreshCheckedStatus();
    this.refreshCheckedReadyAmount();
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
    this.refreshCheckedReadyAmount();
  }

  refreshCheckedReadyAmount(): void {

    this.checkedAmount = 0;
    this.checkUserBackAmount = 0;
    for (let i = 0; i < this.dataList.length; i++) {
      const item = this.dataList[i];
      if (!this.setOfCheckedId.has(item.cpsOrderId)) {
        continue;
      }

      this.checkedAmount = (Number(this.checkedAmount) * 100 + Number(item.orderAmount) * 100) / 100;
      this.checkUserBackAmount = (Number(this.checkUserBackAmount) * 100 + Number(item.userCashBack) * 100) / 100;
    }
  }

  refreshCheckedStatus(): void {
    this.checked = this.dataList.every(item => this.setOfCheckedId.has(item.cpsOrderId));
    this.indeterminate = this.dataList.some(item => this.setOfCheckedId.has(item.cpsOrderId)) && !this.checked;
  }

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  export(): void {
    const startTime = dayjs(this.dates[0]).format('YYYY-MM-DD HH:mm:ss');
    const endTime = dayjs(this.dates[1]).format('YYYY-MM-DD HH:mm:ss');
    this.orderHttpService.exportCpsOrder({
      startTime: startTime,
      endTime: endTime,
      orderNo: this.orderNo,
      mobile: this.mobile,
      userId: this.userId,
      cpsToList: this.cpsTo,
      orderStatusList: this.orderStatus,
      settleStatusList: this.settleStatus
    }, this.exportHttpConfig).subscribe((res) => {
      if (res.msg) {
        window.open(res.msg, '_blank');
      }
    })
  }
}
